import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;

class MyExecutorService{
    //数组容纳线程
    List<Thread> list = new ArrayList<>();
    //队列容纳任务
    BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(10000);
    //构造方法
    public MyExecutorService(int n ){
        for (int i = 0; i < n; i++) {
            //构建线程
            Thread t = new Thread(() ->{
                while(true){
                    try {
                        //此处的take是带有阻塞功能的,如果队列为空,take就会进入阻塞
                        Runnable runnable = queue.take();
                        runnable.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            //启动线程
            t.start();
            //将线程放入线程数组
            list.add(t);
        }
    }
    public void Submit(Runnable runnable){
        queue.offer(runnable);
    }
}
public class ThreadPool {
    public static void main(String[] args) {
        MyExecutorService myExecutorService = new MyExecutorService(4);
        for (int i = 0; i < 1000; i++) {
            int n = i;
            //此时每次循环进来都会新建一个n,n不发生改变为事实final变量
            myExecutorService.Submit(() ->{
                //此处的i涉及到变量捕获,因为i在匿名内部类当中,所以i必须是final或者事实final,事实final就是之后不会改变
                //我们可以在循环外部新设置一个变量n,此时n就是事实final,再将i传入final

                System.out.println("执行任务"+n+" "+"执行线程"+Thread.currentThread().getName());
            });
        }
    }
}
